//
//  SQLiteManager.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/5/4.
//  Copyright © 2016年 Tiffany. All rights reserved.
//

import UIKit

private let DB_NAME = "status.db"

class SQLiteManager: NSObject {
    
    //单例
    static let sharedManager = SQLiteManager()
    
    //创建全局数据库队列
    var queue = FMDatabaseQueue()
    
    override init() {
        super.init()
        //1.数据库的路径
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(DB_NAME)
        print(path)
        
        //2.打开数据库
        queue = FMDatabaseQueue(path: path)
        
        //3.创建表
        createTable()
    }
    
    private func createTable(){
        
        //1.读取sql语句所在的路径
        let sqlPath = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)
        //2.读取aql语句
        let sql = (try! NSString(contentsOfFile: sqlPath!, encoding: NSUTF8StringEncoding)) as String
        
        //3.创建表
        queue.inDatabase { (db) -> Void in
            
            if db.executeUpdate(sql, withArgumentsInArray: nil){
                
                print("创建表成功")
            }else{
                print("创建表失败")
            }
        }
    }
    
    /// 从数组库里面查询出一系列数据出来，每一条数据的格式是字典
    func execRecordSet(sql: String) -> [[String : AnyObject]]{
        
        var result = [[String : AnyObject]]()
        
        SQLiteManager.sharedManager.queue.inDatabase { (db) -> Void in
           let rs = db.executeQuery(sql, withArgumentsInArray: nil)
            
            //rs 为查询到的所有微博数据的集合
            while rs.next(){//查询是否有下一条数据
                
                //定义一个空字典
                var dict = [String : AnyObject]()
                //i 是每一列所对应的行数
                for i in 0..<rs.columnCount() {
                    
                    let key = rs.columnNameForIndex(i) //列名
                    let value = rs.objectForColumnIndex(i)
                    dict[key] = value
                }
                //将该条数据所对应的字典添加到数组中去
                result.append(dict)
            }
        }
        return result
    }
}
